<template>
  <div class="delete-user">
    <h2>删除用户</h2>

    <div v-if="successMessage" class="success">{{ successMessage }}</div>
    <div v-else-if="errorMessage" class="error">{{ errorMessage }}</div>

    <form @submit.prevent="confirmDelete">
      <div class="form-group">
        <label for="userId">请输入要删除的用户ID：</label>
        <input v-model.number="userId" type="number" id="userId" required/>
      </div>

      <button type="submit" :disabled="loading">
        {{ loading ? '删除中...' : '删除用户' }}
      </button>
    </form>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      userId: null,
      loading: false,
      successMessage: '',
      errorMessage: '',
    };
  },
  methods: {
    // 方法一：使用 axios.delete（推荐）
    async confirmDelete() {
      if (!this.userId) {
        this.errorMessage = '请输入有效的用户ID';
        return;
      }

      this.loading = true;
      this.successMessage = '';
      this.errorMessage = '';

      try {
        await axios.delete(`https://jsonplaceholder.typicode.com/users/${this.userId}`);
        this.successMessage = `ID为 ${this.userId} 的用户删除成功！`;
        this.userId = null;
      } catch (err) {
        this.errorMessage = '删除失败，请确认用户ID是否存在或重试。';
        console.error(err);
      } finally {
        this.loading = false;
      }
    },

    // 方法二：使用 axios.request（更灵活）
    /*
    async confirmDelete() {
      if (!this.userId) {
        this.errorMessage = '请输入有效的用户ID';
        return;
      }

      this.loading = true;
      this.successMessage = '';
      this.errorMessage = '';

      try {
        await axios.request({
          method: 'delete',
          url: `https://jsonplaceholder.typicode.com/users/${this.userId}`
        });
        this.successMessage = `ID为 ${this.userId} 的用户删除成功！`;
        this.userId = null;
      } catch (err) {
        this.errorMessage = '删除失败，请确认用户ID是否存在或重试。';
        console.error(err);
      } finally {
        this.loading = false;
      }
    }
    */
  },
};
</script>

<style scoped>
.delete-user {
  max-width: 400px;
  margin: 20px auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 8px;
}

.form-group {
  margin-bottom: 15px;
}

input {
  width: 100%;
  padding: 8px;
  margin-top: 5px;
}

button {
  padding: 10px 15px;
  background-color: #e74c3c;
  color: white;
  border: none;
  cursor: pointer;
}

button:disabled {
  background-color: #aaa;
}

.success {
  color: green;
  margin-bottom: 15px;
}

.error {
  color: red;
  margin-bottom: 15px;
}
</style>